package com.bicon.botu.mall.order.service.impl;


import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.bicon.botu.account.rpc.service.AccountRpcService;
import com.bicon.botu.core.base.common.BusinessException;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.core.base.common.utils.BeanMapper;
import com.bicon.botu.core.base.common.utils.DateUtil;
import com.bicon.botu.core.base.common.utils.IdGen;
import com.bicon.botu.core.base.common.utils.JsonUtil;
import com.bicon.botu.core.base.repository.redis.RedisHandler;
import com.bicon.botu.mall.base.rpc.service.FreightTemplateRpcService;
import com.bicon.botu.mall.base.rpc.service.SystemConfigRpcService;
import com.bicon.botu.mall.member.entity.Address;
import com.bicon.botu.mall.member.rpc.service.AddressRpcService;
import com.bicon.botu.mall.member.rpc.service.CartRpcService;
import com.bicon.botu.mall.order.common.*;
import com.bicon.botu.mall.order.dto.*;
import com.bicon.botu.mall.order.entity.*;
import com.bicon.botu.mall.order.mapper.OrderChildMapper;
import com.bicon.botu.mall.order.mapper.OrderGoodsMapper;
import com.bicon.botu.mall.order.param.OrderChildListParam;
import com.bicon.botu.mall.order.param.OrderChildParam;
import com.bicon.botu.mall.order.param.OrderDetailParam;
import com.bicon.botu.mall.order.processor.handler.*;
import com.bicon.botu.mall.order.service.*;
import com.bicon.botu.mall.order.thirdparty.kdniao.dto.TrackItem;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 子订单Service
 *
 * @author 李双喜
 * @date 2018/5/14 12:57
 */
@Service
@Slf4j
public class OrderChildServiceImpl extends ServiceImpl<OrderChildMapper, OrderChild> implements IOrderChildService {

    //@Autowired
    private ProductRepertoryRpc productRepertoryRpc;

    @Autowired
    private IOrderGoodsService iOrderGoodsService;

    @Autowired
    private IOrderChildService iOrderChildService;

    @Autowired
    private IOrderDetailService iOrderDetailService;

    @Autowired
    private AddressRpcService addressRpc;

    @Autowired
    private IOrderDetailAddressService iOrderDetailAddressService;

    @Autowired
    private OrderGoodsMapper orderGoodsMapper;

    //@Autowired
    private MyCouponsRpc myCouponsRpc;

    @Autowired
    private IMyInvoiceService iMyInvoiceService;

    @Autowired
    private RedisHandler redisHandler;

    @Autowired
    private CartRpcService cartRpc;

    @Autowired
    private OrderChildMapper orderChildMapper;

    //@Autowired
    private PayRpc payRpc;

    @Autowired
    private FreightTemplateRpcService freightTemplateRpcService;

    @Autowired
    private SystemConfigRpcService systemConfigRpcService;

    @Autowired
    private IOrderReceiptService iOrderReceiptService;

    @Autowired
    private IOrderDeliverService iOrderDeliverService;

    @Autowired
    private IOrderRecordsService iOrderRecordsService;

    @Autowired
    private IAfterSalesRecordsService iAfterSalesRecordsService;

    @Autowired
    private AccountRpcService accountRpcService ;


    /**
     * 提交预订单
     *
     * @param jsonString json字符串
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public OrderChildDto affirmOrder(String jsonString, String userId) {

        Type type = new TypeReference<List<OrderChildListParam>>() {
        }.getType();
        List<OrderChildListParam> orderChildListParamList = JSONObject.parseObject(jsonString, type);
        //放入多个商品库存id
        List<String> productRepertoryIdList = new ArrayList<String>();
        //返回结果最大层
        OrderChildDto orderChildDto = new OrderChildDto();
        if (CollectionUtils.isNotEmpty(orderChildListParamList)) {
            //获取默认的地址
            com.bicon.botu.mall.member.dto.DefaultAddressDto adressDefault = addressRpc.getDefault(userId);
            DefaultAddressDto defaultAddressDto = new DefaultAddressDto();
            BeanMapper.copy(adressDefault, defaultAddressDto);
            //多个店铺入参信息,获取到每个店铺所有的商品信息
            List<OrderChildParam> orderChildParams = new ArrayList<>();
            for (OrderChildListParam orderChildListParam : orderChildListParamList) {
                if (CollectionUtils.isNotEmpty(orderChildListParam.getShopList())) {
                    for (OrderChildParam orderChildParam : orderChildListParam.getShopList()) {
                        productRepertoryIdList.add(orderChildParam.getProductRepertoryId());
                        orderChildParams.add(orderChildParam);
                    }
                }
            }
            String product = productRepertoryRpc.selectProductRepertory(productRepertoryIdList.toArray(new String[0]));
            Type t1 = new TypeReference<List<ProductRepertoryIdListDto>>() {
            }.getType();
            //设置所有商品的信息
            List<ProductRepertoryIdListDto> productRepertoryIdListDtoList = JSONObject.parseObject(product, t1);
            List<OrderChildDetailDto> detailDtoList = new ArrayList<>();
            //计算总价
            BigDecimal big1 = new BigDecimal(0);
            //计算运费
            BigDecimal big2 = new BigDecimal(0);
            //计算商品总数
            Integer j = 0;
            String mainOrderNo = OrderUtil.getOrderNo();
            String maxOrderId = IdGen.uuid();
            orderChildDto.setMainOrderId(maxOrderId);
            List<OrderGoods> orderGoodsList = new ArrayList<>();
            List<OrderChild> childList = new ArrayList<>();
            List<OrderDetail> detailList = new ArrayList<>();

            for (OrderChildListParam orderChildListParam : orderChildListParamList) {
                //实例化主订单，订单来源为0表示后面需要传入，订单状态为0标识为预订单
                OrderGoods orderGoods = new OrderGoods(maxOrderId, OrderUtil.getOrderNo(), mainOrderNo, orderChildListParam.getStoreId(), 0, 0);
                if (StringUtils.isNotEmpty(orderChildListParam.getUserId())) {
                    orderGoods.setUser(orderChildListParam.getUserId(), this.checkName(orderChildListParam.getUserId()));
                }
                orderGoods.preInsert();
                OrderChildDetailDto orderChildDetailDto = new OrderChildDetailDto();
                List<OrderGoodsDetailDto> goodsDetailDtoList = new ArrayList<>();
                BigDecimal bigDecimal = new BigDecimal(0);
                BigDecimal bigDecimal1 = new BigDecimal(0);
                BigDecimal yfDecimal = new BigDecimal(0);
                Integer i = 0;
                //定义运费
                BigDecimal yunDecimal = new BigDecimal(0);
                Map<String, OrderChildParam> map = new HashMap<>(16);
                for (OrderChildParam orderChildParam : orderChildListParam.getShopList()) {
                    map.put(orderChildParam.getProductRepertoryId(), orderChildParam);
                }
                List<ProductDTO> productDTOList = new ArrayList<>();
                Map<String, ProductDTO> childProducts = new HashMap<>();
                for (ProductRepertoryIdListDto productRepertoryIdListDto : productRepertoryIdListDtoList) {
                    OrderChildParam orderChildParam = map.get(productRepertoryIdListDto.getId());
                    if (null != orderChildParam) {
                        if (productRepertoryIdListDto.getId().equals(orderChildParam.getProductRepertoryId())) {
                            //子订单详情
                            //因为需要计算子订单运费，在子订单处调用RPC
                            OrderChild orderChild = new OrderChild();
                            ProductDTO productDTO = new ProductDTO();
                            productDTO.setNumber(orderChildParam.getNumber());
                            productDTO.setProductId(productRepertoryIdListDto.getProductId());
                            productDTO.setFreeFreightStatus(productRepertoryIdListDto.getIsFreeFreight());
                            productDTOList.add(productDTO);
                            orderChild.setMainOrderId(orderGoods.getId());
                            orderChild.setUserId(orderChildListParam.getUserId());
                            orderChild.setChildOrderNo(OrderUtil.getOrderNo());
                            orderChild.setOrderType(Integer.valueOf(productRepertoryIdListDto.getProductType()));
                            if (productRepertoryIdListDto.getProductType().equals("1")) {
                                orderChild.setTraceId(orderChildParam.getTraceId());
                            }
                            orderChild.preInsert();
                            orderChild.setStoreId(orderGoods.getStoreId());

                            //订单详情表
                            OrderDetail orderDetail = orderDetailMethod(detailList, orderChildListParam, orderGoods, productRepertoryIdListDto, orderChildParam, orderChild);
                            //计算子订单中的总价
                            orderChild.setTotalPrice(orderDetail.getGoodsPlatformPrice().multiply(new BigDecimal(orderDetail.getGoodsNumber())));
                            childList.add(orderChild);
                            childProducts.put(orderChild.getId(), productDTO);

                            OrderGoodsDetailDto orderGoodsDetailDto = OrderGoodsDetailDtoMethod(productRepertoryIdListDto, orderChildParam);
                            if (productRepertoryIdListDto.getProductType().equals("1")) {
                                orderGoodsDetailDto.setTraceId(orderChildParam.getTraceId());
                            }
                            i += orderChildParam.getNumber();
                            bigDecimal = bigDecimal.add(productRepertoryIdListDto.getProductPrice().multiply(new BigDecimal(orderGoodsDetailDto.getNumber())));
                            if(!childProducts.get(orderChild.getId()).getFreeFreightStatus().equals(OrderConstans.FREE_FREIGHT_NO)) {
                                yfDecimal = yfDecimal.add(productRepertoryIdListDto.getProductPrice().multiply(new BigDecimal(orderGoodsDetailDto.getNumber())));
                            }

                            goodsDetailDtoList.add(orderGoodsDetailDto);
                        }
                    }
                }
                //合并相同的商品id
                Map<String, ProductDTO> productDTOMap = new HashMap<>();
                for (ProductDTO productDTO : productDTOList) {
                    if (productDTOMap.get(productDTO.getProductId()) != null) {
                        productDTOMap.get(productDTO.getProductId()).setNumber(productDTOMap.get(productDTO.getProductId()).getNumber() + productDTO.getNumber());
                    } else {
                        productDTOMap.put(productDTO.getProductId(), productDTO);
                    }
                }
                BaseResult result = freightTemplateRpcService.calcFreight(JSONObject.toJSONString(productDTOMap.values()), defaultAddressDto.getProvince());
                log.info("运费调用结果：" + JSONObject.toJSONString(result));
                if (result.getCode() == Constants.RESPONSE_CODE_200) {
                    if(!result.getData().toString().equals(OrderConstans.freight_NO_0)) {
                        yunDecimal = yunDecimal.add(new BigDecimal(result.getData().toString()));
                        BigDecimal yz = yunDecimal.divide(yfDecimal, 8, BigDecimal.ROUND_HALF_UP);
                        for(OrderChild orderChild : childList) {
                            if(!childProducts.get(orderChild.getId()).getFreeFreightStatus().equals(OrderConstans.FREE_FREIGHT_NO)) {
                                BigDecimal yf = orderChild.getTotalPrice().multiply(yz);
                                BigDecimal newBigDecimal = yf.setScale(2, BigDecimal.ROUND_HALF_UP);
                                orderChild.setFreight(newBigDecimal);
                                orderChild.setPayMoney(orderChild.getTotalPrice().add(orderChild.getFreight()));
                            }
                        }
                    }


                }
                orderChildDetailDto.setShopList(goodsDetailDtoList);
                //添加运费
                orderChildDetailDto.setFreight(yunDecimal);
                orderGoods.setFreight(yunDecimal);
                orderGoodsList.add(orderGoods);
                //返回分组订单id
                orderChildDetailDto.setOrderGoodsId(orderGoods.getId());
                bigDecimal1 = bigDecimal1.add(bigDecimal);
                orderChildDetailDto.setPayment(bigDecimal.add(orderChildDetailDto.getFreight()));
                orderChildDetailDto.setStoreId(orderChildListParam.getStoreId());
                orderChildDetailDto.setTotalNumber(i);
                big1 = big1.add(bigDecimal1);
                big2 = big2.add(orderChildDetailDto.getFreight());
                j += orderChildDetailDto.getTotalNumber();
                detailDtoList.add(orderChildDetailDto);
            }
            orderChildDto.setDetail(detailDtoList);
            orderChildDto.setTotalFreight(big2);
            orderChildDto.setTotalNumber(j);
            orderChildDto.setTotalPrice(big1.add(big2));

            //新增订单组表
            Boolean resultGoods = iOrderGoodsService.insertBatch(orderGoodsList);
            //新增订单商品详情表
            Boolean resultDetail = iOrderDetailService.insertBatch(detailList);
            //新增子订单详情表
            Boolean resultChild = iOrderChildService.insertBatch(childList);
            if (!resultGoods && !resultDetail && !resultChild) {
                throw new BusinessException("更新失败");
            }
            Integer i = systemSettingsInvoice(OrderConstans.INVOICE);
            if (null != i) {
                orderChildDto.setInvoiceState(i);
            }
            //增加订单记录
            String remark = "创建预订单";
            insertOrderRecord(userId, orderGoodsList, remark);
        }
        return orderChildDto;
    }


    /**
     * 订单记录表新增(公共)
     *
     * @param userId         用户id
     * @param orderGoodsList 订单状态等
     * @param remark         备注
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void insertOrderRecord(String userId, List<OrderGoods> orderGoodsList, String remark) {
        String account = null;
        if (StringUtils.isNotEmpty(userId)) {
            account = this.checkName(userId);
        }
        if (CollectionUtils.isNotEmpty(orderGoodsList)) {
            List<OrderRecords> recordsList = new ArrayList<>();
            for (OrderGoods orderGoods : orderGoodsList) {
                OrderRecords records = new OrderRecords();
                records.setOrderGoodsId(orderGoods.getId());
                if (StringUtils.isNotEmpty(account)) {
                    records.setOperator(account);
                } else {
                    records.setOperator("系统");
                }
                records.setOrderState(orderGoods.getPayState());
                records.setStoreId(orderGoods.getStoreId());
                records.setRemark(remark);
                records.preInsert();
                recordsList.add(records);
            }
            boolean result = iOrderRecordsService.insertBatch(recordsList);
            if (!result) {



                throw new BusinessException("更新订单记录失败");
            }
        }
    }

    /**
     * 是否开具发票系统设置
     *
     * @param source
     * @return
     */
    public Integer systemSettingsInvoice(String source) {
        BaseResult baseResult = systemConfigRpcService.getOderConfigValue(source);
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            MallConfigDto mallConfigDto = JSONObject.parseObject(JSONObject.toJSONString(baseResult.getData()), MallConfigDto.class);
            int timeLength = InvoiceEnum.valueOf(mallConfigDto.getDictionaryValue()).getTimeLength();
            return timeLength;
        }
        return null;
    }

    /**
     * 组装参数
     *
     * @param productRepertoryIdListDto
     * @param orderChildParam
     * @return
     */
    private OrderGoodsDetailDto OrderGoodsDetailDtoMethod(ProductRepertoryIdListDto productRepertoryIdListDto, OrderChildParam orderChildParam) {
        OrderGoodsDetailDto orderGoodsDetailDto = new OrderGoodsDetailDto();
        orderGoodsDetailDto.setCustomState(Integer.valueOf(productRepertoryIdListDto.getProductType()));
        orderGoodsDetailDto.setMainPicture(productRepertoryIdListDto.getProductRepertoryPicture());
        orderGoodsDetailDto.setGoodsName(productRepertoryIdListDto.getProductName());
        orderGoodsDetailDto.setProductRepertoryId(productRepertoryIdListDto.getId());
        orderGoodsDetailDto.setGoodsPlatformPrice(productRepertoryIdListDto.getProductPrice());
        orderGoodsDetailDto.setCategoryId(productRepertoryIdListDto.getCategoryId());
        orderGoodsDetailDto.setNumber(orderChildParam.getNumber());
        orderGoodsDetailDto.setGoodsMarketPrice(productRepertoryIdListDto.getProductPrice());
        orderGoodsDetailDto.setSkuName(productRepertoryIdListDto.getSkuName());
        return orderGoodsDetailDto;
    }

    /**
     * 组装参数
     *
     * @param detailList
     * @param orderChildListParam
     * @param orderGoods
     * @param productRepertoryIdListDto
     * @param orderChildParam
     * @param orderChild
     * @return
     */
    private OrderDetail orderDetailMethod(List<OrderDetail> detailList, OrderChildListParam orderChildListParam, OrderGoods orderGoods, ProductRepertoryIdListDto productRepertoryIdListDto, OrderChildParam orderChildParam, OrderChild orderChild) {
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setCategoryId(productRepertoryIdListDto.getCategoryId());
        orderDetail.setGoodsType(productRepertoryIdListDto.getProductType());
        orderDetail.setChildOrderId(orderChild.getId());
        orderDetail.setGoodsId(productRepertoryIdListDto.getId());
        orderDetail.setGoodsMarketPrice(productRepertoryIdListDto.getProductPrice());
        orderDetail.setGoodsPlatformPrice(productRepertoryIdListDto.getProductPrice());
        orderDetail.setGoodsName(productRepertoryIdListDto.getProductName());
        orderDetail.setItemImage(productRepertoryIdListDto.getProductRepertoryPicture());
        orderDetail.setProductCode(productRepertoryIdListDto.getProductCode());
        orderDetail.setGoodsNumber(orderChildParam.getNumber());
        orderDetail.setMainOrderId(orderGoods.getId());
        orderDetail.setSkuName(productRepertoryIdListDto.getSkuName());
        orderDetail.setStoreId(orderChildListParam.getStoreId());
        orderDetail.preInsert();
        detailList.add(orderDetail);
        return orderDetail;
    }


    /**
     * 提交订单接口
     *
     * @param jsonString json字符串
     * @return
     */
    @Override
//    @TxTransaction(isStart = true)
    @Transactional(rollbackFor = Exception.class)
    public BaseResult commitOrder(String jsonString) {
        Type type = new TypeReference<List<OrderDetailParam>>() {
        }.getType();
        //总订单信息
        List<OrderDetailParam> paramList = JSONObject.parseObject(jsonString, type);

        //存入多个分组订单id

        String mainOrderId = null;
        if (CollectionUtils.isNotEmpty(paramList)) {
            //获取到多个分组订单id
            String[] orderGoodsIds = paramList.stream().map(OrderDetailParam::getOrderGoodsId).toArray(String[]::new);
            List<OrderDetail> detailList = iOrderDetailService.selectList(new EntityWrapper<OrderDetail>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL).in("main_order_id", orderGoodsIds));
            List<OrderVerifyDto> verifyDtoList = new ArrayList<>();
            for (OrderDetail orderDetail : detailList) {
                OrderVerifyDto orderVerifyDto = new OrderVerifyDto();
                BeanUtils.copyProperties(orderDetail, orderVerifyDto);
                verifyDtoList.add(orderVerifyDto);
            }
            if (CollectionUtils.isNotEmpty(verifyDtoList)) {
                //验证商品是否可销售
                String result = productRepertoryRpc.verifyProduct(JsonUtil.toJson(verifyDtoList));
                Boolean b = JSONObject.parseObject(result, Boolean.class);
                if (!b) {
                    return new BaseResult(Constants.RESPONSE_CODE_400, "该商品库存不足");
                }
            }
            //查询所有的收货地址
            List<AddressDto> dtoList = new ArrayList();
            String[] address = paramList.stream().map(OrderDetailParam::getAddressId).toArray(String[]::new);
            if (StringUtils.isNotEmpty(address.toString())) {
                List<Address> list = addressRpc.selectAddress(address);
                if (CollectionUtils.isEmpty(list)) {
                    return new BaseResult(400, "地址查询不到");
                }
                dtoList = BeanMapper.mapList(list, AddressDto.class);
            } else {
                return new BaseResult(400, "地址查询不到");
            }
            judgeListMethod(paramList, dtoList);
            //获取到多个分组订单id
            String[] orderGoodsId = paramList.stream().map(OrderDetailParam::getOrderGoodsId).toArray(String[]::new);
            mainOrderId = StringUtils.join(orderGoodsId, ",");
            List<OrderGoods> goodsList = iOrderGoodsService.selectList(new EntityWrapper<OrderGoods>()
                    .in("id", orderGoodsId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            //插入OrderGoods数据库
            Map<String, OrderDetailParam> map = new HashMap(32);

            for (OrderDetailParam orderDetailParam : paramList) {
                map.put(orderDetailParam.getOrderGoodsId(), orderDetailParam);
            }
            if (CollectionUtils.isNotEmpty(goodsList)) {
                String[] myInvoices = paramList.stream().map(OrderDetailParam::getInvoiceId).toArray(String[]::new);
                Map<String, Invoice> appleMap = new HashMap<>(32);
                if (null != myInvoices && myInvoices.length > 0) {
                    List<Invoice> invoiceList = new Invoice().selectList(new EntityWrapper<Invoice>()
                            .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).in("id", myInvoices));
                    //List转Map
                    appleMap = invoiceList.stream().collect(Collectors.toMap(Invoice::getId, a -> a, (k1, k2) -> k1));
                }
                List<MyInvoice> myInvoiceList = new ArrayList<>();
                getOrderGoodsMethod(goodsList, map, appleMap, myInvoiceList);
                Boolean goodsResult = iOrderGoodsService.updateBatchById(goodsList);
                if (!goodsResult) {
                    throw new BusinessException("分组订单更新失败");
                }
                if (CollectionUtils.isNotEmpty(myInvoiceList)) {
                    Boolean result = iMyInvoiceService.insertBatch(myInvoiceList);
                    if (!result) {
                        throw new BusinessException("发票更新失败");
                    }
                }
            }
            //更新子订单表
            List<OrderChild> orderChildList = iOrderChildService.selectList(new EntityWrapper<OrderChild>()
                    .in("main_order_id", orderGoodsId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
            if (CollectionUtils.isNotEmpty(orderChildList)) {
                for (OrderChild orderChild : orderChildList) {
                    OrderDetailParam orderDetailParam = map.get(orderChild.getMainOrderId());
                    orderChild.setUserId(orderDetailParam.getUserId());
                    orderChild.setCreateDate(new Date());
                    //orderChild.setFreight(new BigDecimal(5));
                    orderChild.preUpdate();
                }
                Boolean childResult = iOrderChildService.updateBatchById(orderChildList);
                if (!childResult) {
                    throw new BusinessException("子订单更新失败");
                }
            }
            List<OrderDetailAddress> addressList = new ArrayList<>();
            for (OrderDetailParam orderDetailParam : paramList) {
                //目前优惠券写死
                List<OrderChild> list = new OrderChild().selectList(new EntityWrapper<OrderChild>()
                        .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("main_order_id", orderDetailParam.getOrderGoodsId()));
                if (CollectionUtils.isNotEmpty(list)) {
                    for (OrderChild orderChild : list) {
                        if (StringUtils.isNotEmpty(orderDetailParam.getDiscount())) {
                            orderChild.setDiscountId(orderDetailParam.getDiscount());
                            orderChild.setDiscountMoney(new BigDecimal(99));
                        }
                    }
                    Boolean childResult = iOrderChildService.updateBatchById(list);
                    if (!childResult) {
                        throw new BusinessException("子订单更新失败");
                    }
                }
                //以上等优惠券完成调用rpc，目前写死
                orderDetailAddressMethod(addressList, orderDetailParam);
            }
            Boolean addressResult = iOrderDetailAddressService.insertBatch(addressList);
            List<String> useIds = paramList.stream().map(OrderDetailParam::getUserId).collect(Collectors.toList());
            //查询商品skuId,去删除购物车数据库
            List<OrderDetail> orderDetailList = iOrderDetailService.selectList(new EntityWrapper<OrderDetail>()
                    .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).in("main_order_id", orderGoodsIds));
            List<String> skuIdList = orderDetailList.stream().map(OrderDetail::getGoodsId).collect(Collectors.toList());
            Boolean cartResult = cartRpc.deleteCart(skuIdList, useIds.get(0));
            if (!cartResult && !addressResult) {
                return new BaseResult(500, "购物车删除失败");
            }
            //增加订单记录
            String remark = "创建订单成功";
            insertOrderRecord(useIds.get(0), goodsList, remark);
        }
        return new BaseResult(200, "success", mainOrderId);
    }

    /**
     * 获取订单商品List
     *
     * @param goodsList
     * @param map
     * @param appleMap
     * @param myInvoiceList
     */
    private void getOrderGoodsMethod(List<OrderGoods> goodsList, Map<String, OrderDetailParam> map, Map<String, Invoice> appleMap, List<MyInvoice> myInvoiceList) {
        for (OrderGoods orderGoods : goodsList) {
            OrderDetailParam orderDetailParam = map.get(orderGoods.getId());
            if (null != orderDetailParam) {
                orderGoods.setUserId(orderDetailParam.getUserId());
                orderGoods.setAccount(this.checkName(orderDetailParam.getUserId()));
                orderGoods.setPayState(1);
                if (StringUtils.isNotEmpty(orderDetailParam.getBuyerMessage())) {
                    orderGoods.setBuyerMessage(orderDetailParam.getBuyerMessage());
                }
                if (StringUtils.isNotEmpty(orderDetailParam.getInvoiceId())) {
                    Invoice invoice = appleMap.get(orderDetailParam.getInvoiceId());
                    MyInvoice myInvoice = new MyInvoice();
                    BeanUtils.copyProperties(invoice, myInvoice);
                    myInvoice.preInsert();
                    myInvoiceList.add(myInvoice);
                    orderGoods.setInvoiceId(myInvoice.getId());
                }
                orderGoods.setCreateDate(new Date());
                orderGoods.preUpdate();
                orderGoods.setDistributionWay(orderDetailParam.getDistributionWay());
                orderGoods.setOrderSource(orderDetailParam.getOrderSource());
            }
        }
    }

    /**
     * 组装参数
     *
     * @param addressList
     * @param orderDetailParam
     */
    private void orderDetailAddressMethod(List<OrderDetailAddress> addressList, OrderDetailParam orderDetailParam) {
        OrderDetailAddress orderDetailAddress = new OrderDetailAddress();
        orderDetailAddress.setOrderGoodsId(orderDetailParam.getOrderGoodsId());
        orderDetailAddress.setUserId(orderDetailParam.getUserId());
        orderDetailAddress.setAddressDetail(orderDetailParam.getAddressDetailed());
        orderDetailAddress.setName(orderDetailParam.getAddressName());
        orderDetailAddress.setArea(orderDetailParam.getAddressArea());
        orderDetailAddress.setCity(orderDetailParam.getAddressCity());
        orderDetailAddress.setTelephone(orderDetailParam.getAddressPhone());
        orderDetailAddress.setProvince(orderDetailParam.getAddressProvince());
        orderDetailAddress.setPostCode(orderDetailParam.getAddressZip());
        orderDetailAddress.preInsert();
        addressList.add(orderDetailAddress);
    }

    private void judgeListMethod(List<OrderDetailParam> paramList, List<AddressDto> dtoList) {
        if (CollectionUtils.isNotEmpty(dtoList)) {
            for (AddressDto addressDto : dtoList) {
                for (OrderDetailParam orderDetailParam : paramList) {
                    if (addressDto.getId().equals(orderDetailParam.getAddressId())) {
                        orderDetailParam.setAddressId(addressDto.getId());
                        BeanUtils.copyProperties(addressDto, orderDetailParam);
                    }
                }
            }
        }
    }

    /**
     * 根据总订单id删除预订单
     *
     * @param id 总订单id
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean deleteMaxOrder(String id) {
        List<OrderGoods> goodsList = iOrderGoodsService.selectList(new EntityWrapper<OrderGoods>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("max_order_id", id));
        if (CollectionUtils.isNotEmpty(goodsList)) {
            List<String> listId = new ArrayList<>();
            for (OrderGoods orderGoods : goodsList) {
                listId.add(orderGoods.getId());
            }
            iOrderGoodsService.delete(new EntityWrapper<OrderGoods>().in("max_order_id", id));

            iOrderChildService.delete(new EntityWrapper<OrderChild>().in("main_order_id", listId));

            iOrderDetailService.delete(new EntityWrapper<OrderDetail>().in("main_order_id", listId));

            //删除预订单订单记录
            String remark = "删除预订单成功";
            insertOrderRecord(goodsList.get(0).getUserId(), goodsList, remark);
            return true;
        }
        return false;
    }

    /**
     * 查询订单详情接口
     *
     * @param orderGoodsId 分组订单id
     * @return
     */
    @Override
    public OrderDetailDto selectDetail(String orderGoodsId) {
        OrderGoods orderGoods = iOrderGoodsService.selectOne(new EntityWrapper<OrderGoods>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("id", orderGoodsId));
        if (null == orderGoods) {
            throw new BusinessException("订单信息不存在");
        }
        OrderDetailDto orderDetailDto = new OrderDetailDto();
        orderDetailDto.setEvaluateState(orderGoods.getEvaluateState());
        orderDetailDto.setMaxOrderId(orderGoods.getMaxOrderId());
        //默认显示售后按钮
        orderDetailDto.setQuitShowStatus(OrderConstans.QUIT_SHOW_STATUS_OPEN);
        if (StringUtils.isNotEmpty(orderGoods.getBuyerMessage())) {
            orderDetailDto.setBuyerMessage(orderGoods.getBuyerMessage());
        }
        stateMethod(orderGoodsId, orderGoods, orderDetailDto);
        List<OrderDetail> detailList = iOrderDetailService.selectList(new EntityWrapper<OrderDetail>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("main_order_id", orderGoodsId));
        if (CollectionUtils.isEmpty(detailList)) {
            throw new BusinessException("商品信息不存在");
        }
        List<OrderGoodsDetailDto> detailDtoList = new ArrayList<>();
        int i = 0;
        BigDecimal big = new BigDecimal(0);
        Map<String, OrderGoodsDetailDto> dtoMap = new HashMap<>(32);
        for (OrderDetail orderDetail : detailList) {
            OrderGoodsDetailDto orderGoodsDetailDto = new OrderGoodsDetailDto();
            if (null != orderDetail.getGoodsPlatformPrice()) {
                big = big.add(orderDetail.getGoodsPlatformPrice());
            }
            orderGoodsDetailDto.setCategoryId(orderDetail.getCategoryId());
            orderGoodsDetailDto.setProductRepertoryId(orderDetail.getGoodsId());
            if (StringUtils.isNotBlank(orderDetail.getGoodsId())) {
                String resultJson = productRepertoryRpc.selectProductById(orderDetail.getGoodsId());
                if (StringUtils.isNotBlank(resultJson)) {
                    ProductRepertoryDto repertoryDto = JSONObject.parseObject(resultJson, ProductRepertoryDto.class);
                    orderGoodsDetailDto.setProductId(repertoryDto.getProductId());
                }
            }
            orderGoodsDetailMethod(orderDetail, orderGoodsDetailDto);
            i += orderDetail.getGoodsNumber();
            dtoMap.put(orderGoodsDetailDto.getOrderChildId(), orderGoodsDetailDto);
            detailDtoList.add(orderGoodsDetailDto);
        }
        orderDetailDtoMethod(orderGoods, orderDetailDto, detailDtoList, i, big);
        List<OrderChild> childList = iOrderChildService.selectList(new EntityWrapper<OrderChild>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("main_order_id", orderGoodsId));
        Set<Integer> set = new HashSet<>();
        if (CollectionUtils.isNotEmpty(childList)) {
            BigDecimal bigDecimal = new BigDecimal(0);
            BigDecimal discount = new BigDecimal(0);
            BigDecimal pagMoney = new BigDecimal(0);
            List<String> discountId = new ArrayList<>();
            for (OrderChild orderChild : childList) {
                if (null != dtoMap) {
                    OrderGoodsDetailDto orderGoodsDetailDto = dtoMap.get(orderChild.getId());
                    orderGoodsDetailDto.setEvaluateState(orderChild.getEvaluateState());
                    orderGoodsDetailDto.setQuitState(orderChild.getQuitState());
                    set.add(orderGoodsDetailDto.getQuitState());
                    if (StringUtils.isNotEmpty(orderChild.getAfterSaleRecordId())) {
                        orderGoodsDetailDto.setAfterSaleRecordId(orderChild.getAfterSaleRecordId());
                    }
                }
                if (null != orderChild.getPayMoney()) {
                    pagMoney = pagMoney.add(orderChild.getPayMoney());
                }
                if (StringUtils.isNotEmpty(orderChild.getDiscountId())) {
                    discountId.add(orderChild.getDiscountId());
                }
                if (null != orderChild.getDiscountMoney()) {
                    discount = discount.add(orderChild.getDiscountMoney());
                    bigDecimal = bigDecimal.add(orderChild.getTotalPrice()).subtract(orderChild.getDiscountMoney());
                } else {
                    bigDecimal = bigDecimal.add(orderChild.getTotalPrice());
                }
            }
            orderDetailDto.setPayMoney(pagMoney);
            orderDetailDto.setDiscountId(discountId);
            bigDecimal = bigDecimal.add(orderDetailDto.getFreight());
            orderDetailDto.setPayment(bigDecimal);
            orderDetailDto.setTotalDiscount(discount);
        }
        orderDetailDto.setStoreId(orderGoods.getStoreId());
        orderDetailDto.setOrderGoodsId(orderGoods.getId());
        if (StringUtils.isNotEmpty(orderGoods.getInvoiceId())) {
            MyInvoice myInvoice = iMyInvoiceService.selectById(orderGoods.getInvoiceId());
            orderDetailDto.setMyInvoice(myInvoice);
        }
        orderDetailDto.setOrderGoodsNo(orderGoods.getOrderGoodsNo());
        OrderDetailAddress orderDetailAddress = iOrderDetailAddressService.selectOne(new EntityWrapper<OrderDetailAddress>().eq("main_order_id", orderGoodsId));
        selectAddressDetailMethod(orderDetailDto, orderDetailAddress);
        if (set.contains(0)) {
            orderDetailDto.setApplicationState(0);
        } else {
            orderDetailDto.setApplicationState(1);
        }
        orderDetailDto.setContactWay("400-7675-8656");
        return orderDetailDto;
    }

    /**
     * 组装参数
     *
     * @param orderGoods
     * @param orderDetailDto
     * @param detailDtoList
     * @param i
     * @param big
     */
    private void orderDetailDtoMethod(OrderGoods orderGoods, OrderDetailDto orderDetailDto, List<OrderGoodsDetailDto> detailDtoList, int i, BigDecimal big) {
        orderDetailDto.setGoodsTogether(big);
        orderDetailDto.setShopList(detailDtoList);
        orderDetailDto.setTotalNumber(i);
        orderDetailDto.setCreateDate(orderGoods.getCreateDate());
        orderDetailDto.setFreight(orderGoods.getFreight());
        orderDetailDto.setDistributionWay(orderGoods.getDistributionWay());
    }

    /**
     * 组装参数
     *
     * @param orderDetail
     * @param orderGoodsDetailDto
     */
    private void orderGoodsDetailMethod(OrderDetail orderDetail, OrderGoodsDetailDto orderGoodsDetailDto) {
        orderGoodsDetailDto.setOrderChildId(orderDetail.getChildOrderId());
        orderGoodsDetailDto.setNumber(orderDetail.getGoodsNumber());
        orderGoodsDetailDto.setGoodsName(orderDetail.getGoodsName());
        orderGoodsDetailDto.setCustomState(Integer.valueOf(orderDetail.getGoodsType()));
        orderGoodsDetailDto.setGoodsPlatformPrice(orderDetail.getGoodsPlatformPrice());
        orderGoodsDetailDto.setMainPicture(orderDetail.getItemImage());
        orderGoodsDetailDto.setGoodsMarketPrice(orderDetail.getGoodsMarketPrice());
        orderGoodsDetailDto.setSkuName(orderDetail.getSkuName());
    }

    /**
     * 详情状态判断
     *
     * @param orderGoodsId
     * @param orderGoods
     * @param orderDetailDto
     */
    private void stateMethod(String orderGoodsId, OrderGoods orderGoods, OrderDetailDto orderDetailDto) {
        if (OrderConstans.ORDER_STATUS_1.equals(orderGoods.getPayState())) {
            unpaidMethod(orderGoods, orderDetailDto);
        } else if (OrderConstans.ORDER_STATUS_2.equals(orderGoods.getPayState())) {
            paidMethod(orderGoods, orderDetailDto);
        } else if (OrderConstans.ORDER_STATUS_3.equals(orderGoods.getPayState())) {
            receivingMethod(orderGoodsId, orderGoods, orderDetailDto);
        } else if (OrderConstans.ORDER_STATUS_4.equals(orderGoods.getPayState())) {
            successfulDealMethod(orderGoodsId, orderGoods, orderDetailDto);
        } else if (OrderConstans.ORDER_STATUS_5.equals(orderGoods.getPayState())) {
            orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_5);
        } else if (OrderConstans.ORDER_STATUS_6.equals(orderGoods.getPayState())) {
            orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_6);
            if (null == orderGoods.getPayWay()) {
                orderDetailDto.setPayWay(-1);
            } else {
                orderDetailDto.setPayWay(orderGoods.getPayWay());
            }
            orderDetailDto.setStateSlogan(orderGoods.getCancelOrder());
        } else if (OrderConstans.ORDER_STATUS_7.equals(orderGoods.getPayState())) {
            orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_7);
        }
    }

    /**
     * 地址详情
     *
     * @param orderDetailDto
     * @param orderDetailAddress
     */
    private void selectAddressDetailMethod(OrderDetailDto orderDetailDto, OrderDetailAddress orderDetailAddress) {
        if (null != orderDetailAddress) {
            AddressDetailDto addressDetailDto = new AddressDetailDto();
            addressDetailDto.setId(orderDetailAddress.getId());
            addressDetailDto.setAddressName(orderDetailAddress.getName());
            addressDetailDto.setAddressPhone(orderDetailAddress.getTelephone());
            addressDetailDto.setAddressDetail(orderDetailAddress.getProvince() + orderDetailAddress.getCity() + orderDetailAddress.getArea() + orderDetailAddress.getAddressDetail());
            addressDetailDto.setProvince(orderDetailAddress.getProvince());
            addressDetailDto.setCity(orderDetailAddress.getCity());
            addressDetailDto.setArea(orderDetailAddress.getArea());
            addressDetailDto.setAddressMark(orderDetailAddress.getAddressDetail());
            orderDetailDto.setAddress(addressDetailDto);
        }
    }

    /**
     * 交易成功
     *
     * @param orderGoodsId
     * @param orderGoods
     * @param orderDetailDto
     */
    private void successfulDealMethod(String orderGoodsId, OrderGoods orderGoods, OrderDetailDto orderDetailDto) {
        OrderReceipt orderReceipt = iOrderReceiptService.selectById(orderGoods.getOrderReceiptId());
        if (null != orderReceipt) {
            orderDetailDto.setTransactionNo(orderReceipt.getTransactionNo());
        }
        orderDetailDto.setPayWay(orderGoods.getPayWay());
        orderDetailDto.setDealTime(orderGoods.getDealTime());
        orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_4);
        OrderLogisticsDto orderLogisticsDto = iOrderDeliverService.getLogistics(orderGoodsId);
        verifyOrderMethod(orderDetailDto, orderLogisticsDto);
        //判断售后按钮是否可见
        BaseResult baseResult = systemConfigRpcService.getOderConfigValue(OrderConstans.AFTER_SALE_CLOSE);
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            MallConfigDto mallConfigDto = JSONObject.parseObject(JSONObject.toJSONString(baseResult.getData()), MallConfigDto.class);
            int timeLength = CloseOrderEnum.valueOf(mallConfigDto.getDictionaryValue()).getTimeLength();
            if (timeLength > 0) {
                int day = DateUtil.calculateIntervalDays(orderGoods.getDealTime(), new Date());
                if (day >= timeLength) {
                    orderDetailDto.setQuitShowStatus(OrderConstans.QUIT_SHOW_STATUS_CLOSE);
                }
            }
        }
    }

    /**
     * 待收货状态
     *
     * @param orderGoodsId
     * @param orderGoods
     * @param orderDetailDto
     */
    private void receivingMethod(String orderGoodsId, OrderGoods orderGoods, OrderDetailDto orderDetailDto) {
        OrderReceipt orderReceipt = iOrderReceiptService.selectById(orderGoods.getOrderReceiptId());
        if (null != orderReceipt) {
            orderDetailDto.setTransactionNo(orderReceipt.getTransactionNo());
        }
        orderDetailDto.setPayWay(orderGoods.getPayWay());
        orderDetailDto.setPayTime(orderGoods.getPayTime());
        OrderDeliver orderDeliver = iOrderDeliverService.selectOne(new EntityWrapper<OrderDeliver>()
                .eq("id", orderGoods.getOrderDeliverId()).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        Integer integer = systemSettings(OrderConstans.CINFIRM_RECEIPT);
        if (integer > 0) {
            Date create = orderDeliver.getCreateDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sd = sdf.format(new Date(Long.parseLong(String.valueOf(create.getTime()))));
            String a = StringUtils.replace(sd, " ", "T");
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime createTime = LocalDateTime.parse(a);
            createTime.plusDays(1);

            Long result = 24 * integer - Duration.between(createTime, now).toHours();
            Long b = result / 24;
            if (b <= 0) {
                b = 0L;
            }
            Long c = result % 24;
            if (c <= 0) {
                c = 0L;
            }
            String d = String.valueOf(c);
            if (d.length() == 1) {
                d = "0" + c;
            }
            orderDetailDto.setStateSlogan("剩余" + b + "天" + d + "时" + "将自动确认收货");
        }
        orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_3);
        OrderLogisticsDto orderLogisticsDto = iOrderDeliverService.getLogistics(orderGoodsId);
        verifyOrderMethod(orderDetailDto, orderLogisticsDto);
    }


    /**
     * 自动发货-调用系统设置是否开启和关闭功能项（开启提示时间）
     */
    public Integer systemSettings(String source) {
        BaseResult baseResult = systemConfigRpcService.getOderConfigValue(source);
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            MallConfigDto mallConfigDto = JSONObject.parseObject(JSONObject.toJSONString(baseResult.getData()), MallConfigDto.class);
            int timeLength = CollectEnum.valueOf(mallConfigDto.getDictionaryValue()).getTimeLength();
            return timeLength;
        }
        return null;
    }

    /**
     * 已支付状态
     *
     * @param orderGoods
     * @param orderDetailDto
     */
    private void paidMethod(OrderGoods orderGoods, OrderDetailDto orderDetailDto) {
        orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_2);
        orderDetailDto.setPayWay(orderGoods.getPayWay());
        orderDetailDto.setPayTime(orderGoods.getPayTime());
        OrderReceipt orderReceipt = iOrderReceiptService.selectById(orderGoods.getOrderReceiptId());
        if (null != orderReceipt) {
            orderDetailDto.setTransactionNo(orderReceipt.getTransactionNo());
        }
    }

    /**
     * 取消订单的系统设置
     *
     * @param source
     * @return
     */
    public Integer systemSettingsUnpaid(String source) {
        BaseResult baseResult = systemConfigRpcService.getOderConfigValue(source);
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            MallConfigDto mallConfigDto = JSONObject.parseObject(JSONObject.toJSONString(baseResult.getData()), MallConfigDto.class);
            int timeLength = CancelEnum.valueOf(mallConfigDto.getDictionaryValue()).getTimeLength();
            return timeLength;
        }
        return null;
    }

    /**
     * 待支付状态
     *
     * @param orderGoods
     * @param orderDetailDto
     */
    private void unpaidMethod(OrderGoods orderGoods, OrderDetailDto orderDetailDto) {
        orderDetailDto.setPayState(OrderConstans.ORDER_STATUS_1);
        Integer integer = systemSettingsUnpaid(OrderConstans.CANCEL_ORDER);
        if (integer > 0) {
            Date create = orderGoods.getCreateDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String sd = sdf.format(new Date(Long.parseLong(String.valueOf(create.getTime()))));
            String a = StringUtils.replace(sd, " ", "T");
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime createTime = LocalDateTime.parse(a);
            createTime.plusDays(1);

            Long result = integer * 60 - Duration.between(createTime, now).toMinutes();
            Long b = result / 60;
            if (b <= 0) {
                b = 0L;
            }
            Long c = result % 60;
            if (c <= 0) {
                c = 0L;
            }
            String d = String.valueOf(c);
            if (d.length() == 1) {
                d = "0" + c;
            }
            orderDetailDto.setStateSlogan("剩余" + b + "时" + d + "分" + "交易自动关闭");
        }
        orderDetailDto.setPayWay(-1);
    }

    /**
     * 查询订单详情最新物流
     *
     * @param orderDetailDto
     * @param orderLogisticsDto
     */
    public void verifyOrderMethod(OrderDetailDto orderDetailDto, OrderLogisticsDto orderLogisticsDto) {
        if (null != orderLogisticsDto && CollectionUtils.isNotEmpty(orderLogisticsDto.getTraces())) {
            List<TrackItem> trackItemList = orderLogisticsDto.getTraces();
            TrackItem trackItem = trackItemList.get(0);
            LogisticsDto logisticsDto = new LogisticsDto();
            logisticsDto.setLogistics(trackItem.getAcceptStation());
            logisticsDto.setDate(trackItem.getAcceptTime());
            orderDetailDto.setLogistics(logisticsDto);
        }
    }

    /**
     * web端订单详情接口
     *
     * @param orderGoodsId 分组订单id
     * @return
     */

    @Override
    public BaseResult selectOrderDetail(String orderGoodsId) {
        //调用api的查询详情接口信息
        OrderDetailDto orderDetailDto = this.selectDetail(orderGoodsId);
        OrderDetailWebDto orderDetailWebDto = new OrderDetailWebDto();
        BeanUtils.copyProperties(orderDetailDto, orderDetailWebDto);
        OrderGoods orderGoods = iOrderGoodsService.selectOne(new EntityWrapper<OrderGoods>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("id", orderGoodsId));
        orderDetailWebDto.setOrderSource(orderGoods.getOrderSource());
        if (CollectionUtils.isNotEmpty(orderDetailDto.getDiscountId())) {
            String discountName = myCouponsRpc.selectMyCoupons(orderDetailDto.getDiscountId());
            Type t1 = new TypeReference<List<String>>() {
            }.getType();
            List<String> discountNameList = JSONObject.parseObject(discountName, t1);
            orderDetailWebDto.setDiscount(discountNameList);
        }
        orderDetailWebDto.setUserId(orderGoods.getUserId());
        String name = this.checkName(orderGoods.getUserId());
        if (StringUtils.isNotEmpty(name)) {
            orderDetailWebDto.setUserName(name);
        }
        return new BaseResult(200, "success", orderDetailWebDto);

    }


    /**
     * 查询用户账号
     *
     * @param userId 用户id
     * @return
     */
    @Override
    public String checkName(String userId) {
        BaseResult<AccountInfoDTO> baseResult = accountRpcService.getAccountLog(userId);
        if (baseResult.getCode() == 200) {
            AccountInfoDTO dto = baseResult.getData();
//            AccountInfoDTO dto = JSONObject.parseObject(JSONObject.toJSONString(object),AccountInfoDTO.class);
            if (null != dto) {
                return dto.getAccount();
            } else {
                throw new BusinessException("账号信息获取失败");
            }
        } else {
            throw new BusinessException("账号信息获取失败");
        }
    }


    /**
     * 统计订单信息
     *
     * @param storeId 店铺id
     * @return
     */

    @Override
    public OrderTotalDto selectOrderTotal(String storeId) {
        OrderTotalDto orderTotalDto = new OrderTotalDto();
        Integer refund = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 7));
        Integer unpaid = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 1));
        orderTotalDto.setUnpaid(unpaid);
        Integer wait = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 2));
        orderTotalDto.setWait(wait);
        Integer shipped = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 3));
        orderTotalDto.setShipped(shipped);
        Integer complete = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 4));
        orderTotalDto.setComplete(complete);
        Integer cancel = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 6));
        orderTotalDto.setCancel(cancel);
        Integer close = iOrderGoodsService.selectCount(new EntityWrapper<OrderGoods>()
                .eq("store_id", storeId).eq("pay_state", 5));
        orderTotalDto.setClose(close);
        orderTotalDto.setTotal(refund + unpaid + wait + shipped + complete + cancel + close);
        //售后待处理
        Integer pending = iAfterSalesRecordsService.selectCount(new EntityWrapper<AfterSalesRecords>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("status", 1));
        orderTotalDto.setPending(pending);
        //售后处理中
        List<Integer> list = new ArrayList<>();
        list.add(2);
        list.add(3);
        list.add(4);
        Integer processing = iAfterSalesRecordsService.selectCount(new EntityWrapper<AfterSalesRecords>()
                .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).in("status", list));
        orderTotalDto.setProcessing(processing);
        return orderTotalDto;
    }

    /**
     * 根据订单ID 查询子订单商品列表
     *
     * @param page
     * @param orderGoodsId
     * @return
     */
    @Override
    public Page<ChildAndDetailDto> getOrderInfoByOrderGoodsId(Page<ChildAndDetailDto> page, String orderGoodsId) {
        page.setRecords(orderChildMapper.getOrderInfoByOrderGoodsId(page, orderGoodsId));
        return page;
    }

    /**
     * 根据订单ID 获得商品价格总和
     *
     * @param orderGoodsId
     * @return
     */
    @Override
    public double getSumTotalPrice(String orderGoodsId) {
        return orderChildMapper.getSumTotalPrice(orderGoodsId);
    }

    /**
     * 订单支付接口(因目前rpc未处理支持单店铺)
     *
     * @param userId     转账人
     * @param maxOrderId 多个分组订单id
     * @param channel    支付类型 0余额 1 支付宝 2微信
     * @param toUserId   接收人
     * @param password   密码
     * @return
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public BaseResult pay(String userId, String maxOrderId, String channel, String toUserId, String password) {
        String[] ids = maxOrderId.split(",");
        //多个店铺下的分组订单（目前只有一个店铺）
        OrderGoods orderGoods = iOrderGoodsService.selectOne(new EntityWrapper<OrderGoods>().in("id", ids).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        if (null == orderGoods) {
            return new BaseResult(602, "该订单已不存在");
        }
        List<String> list = new ArrayList<String>();
        //计算总的运费
        BigDecimal totalFreight = new BigDecimal(0);
        orderGoods.setPayTime(new Date());
        orderGoods.setPayWay(Integer.valueOf(channel));
        list.add(orderGoods.getId());
        totalFreight = totalFreight.add(orderGoods.getFreight());
        //总的商品的总价-总的优惠金额+总运费 = 支付总金额
        BigDecimal big = new BigDecimal(0);
        //批量查询订单的汇总金额
        List<OrderChild> childList = this.selectList(new EntityWrapper<OrderChild>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL)
                .in("main_order_id", list));
        if (CollectionUtils.isEmpty(childList)) {
            return new BaseResult(602, "该订单已不存在");
        } else {
            //商品总价
            BigDecimal totalGoodsPrice = new BigDecimal(0);
            //优惠总金额
            BigDecimal totalDiscount = new BigDecimal(0);
            for (OrderChild orderChild : childList) {
                orderChild.setPayMoney(orderChild.getTotalPrice().add(orderChild.getFreight().subtract(orderChild.getDiscountMoney())));
                orderChild.preUpdate();
                totalGoodsPrice = totalGoodsPrice.add(orderChild.getTotalPrice());
                totalDiscount = totalDiscount.add(orderChild.getDiscountMoney());
            }
            //更新子订单的实际支付金额
            this.updateBatchById(childList);
            //商品总价 + 运费 - 优惠金额 = 支付金额
            big = big.add(totalGoodsPrice.subtract(totalDiscount).add(totalFreight));
            //增加一条收款信息
            OrderReceipt orderReceipt = new OrderReceipt();
            if (StringUtils.isNotEmpty(orderGoods.getOrderReceiptId())) {
                orderReceipt = new OrderReceipt().selectOne(new EntityWrapper<OrderReceipt>()
                        .eq("logic_delete", Constants.DEL_LOGIC_NORMAL).eq("id", orderGoods.getOrderReceiptId()));
            }
            orderReceipt.setMainOrderId(list.get(0));
            orderReceipt.setMoney(big);
            orderReceipt.setReceiptNo(OrderUtil.getOrderNo());
            orderReceipt.setUserId(userId);
            orderReceipt.setStoreId(orderGoods.getStoreId());
            //根据支付总金额调用接收人的账号
            //big.doubleValue()
            String json = payRpc.gratuity("mall", "order", userId, 0.1, "admin", password, "", channel, OrderConstans.Order_SENSITIVEWORD);
            Type t = new TypeReference<BaseResult<Map<String, Object>>>() {
            }.getType();
            Map<String, Object> map = null;
            BaseResult<Map<String, Object>> baseResult = null;
            baseResult = JSONObject.parseObject(json, t);
            if (baseResult.getCode() != Constants.RESPONSE_CODE_200) {
                return baseResult;
            }
            map = baseResult.getData();
            Type tt = new TypeReference<WalletDetailVO>() {
            }.getType();
            WalletDetailVO walletDetailVO = JSONObject.parseObject(map.get("order").toString(), tt);
            if (null != walletDetailVO && walletDetailVO.getState().equals("2")) {
                return new BaseResult(600, "交易失败");
            } else if (null != walletDetailVO && walletDetailVO.getState().equals("3")) {
                return new BaseResult(600, "交易已取消");
            } else {
                if (StringUtils.isNotEmpty(walletDetailVO.getOrderNo())) {
                    orderReceipt.setTransactionNo(walletDetailVO.getOrderNo());
                }
                if (channel.equals("0")) {
                    orderReceipt.setPayState(Integer.valueOf(OrderConstans.WALLET_STATE_SUCCESS));
                    orderGoods.setPayState(2);
                    //增加销量
                    addSales(orderGoods.getId());
                } else if (channel.equals("1") || channel.equals("2")) {
                    orderGoods.setPayState(1);
                    orderReceipt.setPayState(Integer.valueOf(OrderConstans.WALLET_STATE_ING));
                }
            }
            if (StringUtils.isEmpty(orderGoods.getOrderReceiptId())) {
                orderReceipt.preInsert();
                orderReceipt.insert();
            } else {
                orderReceipt.preUpdate();
                orderReceipt.updateById();
            }
            orderGoods.preUpdate();
            orderGoods.setOrderReceiptId(orderReceipt.getId());
            Boolean result = iOrderGoodsService.updateById(orderGoods);
            List<OrderGoods> orderGoodsList = new ArrayList<>();
            orderGoodsList.add(orderGoods);
            //删除预订单
            String remark = "订单支付";
            insertOrderRecord(orderGoods.getUserId(), orderGoodsList, remark);

            if (!result) {
                return new BaseResult(500, "支付失败");
            }
            return new BaseResult(200, "success", map);
        }
    }

    /**
     * 增加销量
     *
     * @param orderGoodId
     */
    @Override
    public void addSales(String orderGoodId) {
        List<OrderDetail> details = new OrderDetail().selectList(new EntityWrapper<OrderGoods>().eq("main_order_id", orderGoodId).eq("logic_delete", 0));
        OrderVerifyDto verifyDto;
        List<OrderVerifyDto> list = new ArrayList<>();
        for (OrderDetail detail : details) {
            verifyDto = new OrderVerifyDto(detail.getGoodsId(), detail.getGoodsNumber());
            list.add(verifyDto);
        }
        BaseResult baseResult = productRepertoryRpc.rollbackNum(JSONObject.toJSONString(list));
        if (baseResult.getCode() == Constants.RESPONSE_CODE_200) {
            if ((boolean) baseResult.getData()) {
                log.info("订单：" + orderGoodId + "，添加销量成功");
            }
        }
    }

    /**
     * 根椐订单ID获得其子订单个数及已评价的子订单总数
     *
     * @param orderGoodsId 订单ID
     * @return
     */
    @Override
    public Map<String, Long> getEvaluateState(String orderGoodsId) {
        return orderChildMapper.getEvaluateState(orderGoodsId);
    }

    /**
     * 根据子订单ID集合，修改订单评价状态
     *
     * @param orderChildIds
     * @return
     */
    @Override
    public boolean updateEvaluateState(List<String> orderChildIds) {
        return retBool(orderChildMapper.updateEvaluateState(orderChildIds));
    }

    /**
     * 计算和更新预订单运费信息
     *
     * @param paramList 分组订单Id列表
     * @return
     */
    @Override
    public OrderChildDto freightCalculate(List<OrderDetailParam> paramList) {
        OrderChildDto result = new OrderChildDto();
        //分组订单
        GoodsAndProductDto goodsAndProductDto;
        Map<String, GoodsAndProductDto> goodsMap = new HashMap<>(16);
        for (OrderDetailParam orderDetailParam : paramList) {
            goodsAndProductDto = new GoodsAndProductDto();
            goodsAndProductDto.setOrderDetailParam(orderDetailParam);
            goodsMap.put(orderDetailParam.getOrderGoodsId(), goodsAndProductDto);
        }
        String[] orderGoodsId = paramList.stream().map(OrderDetailParam::getOrderGoodsId).toArray(String[]::new);
        String goodIds = "('" + StringUtils.join(orderGoodsId, "','") + "')";
        List<GoodsAndDetailDto> detailDtos = orderChildMapper.selectOrderDetail(goodIds);
        List<ProductDTO> productDTOList;

        //初始化所有的订单
        List<OrderGoods> goodsList = iOrderGoodsService.selectList(new EntityWrapper<OrderGoods>()
                .in("id", orderGoodsId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));
        //查询所有的收货地址
        List<AddressDto> dtoList = new ArrayList();
        String[] address = paramList.stream().map(OrderDetailParam::getAddressId).toArray(String[]::new);
        if (StringUtils.isNotEmpty(address.toString())) {
            List<Address> addresses = addressRpc.selectAddress(address);
            if (CollectionUtils.isEmpty(addresses)) {
                throw new BusinessException("地址查询不到");
            }

            dtoList = BeanMapper.mapList(addresses, AddressDto.class);
        } else {
            throw new BusinessException("地址查询不到");
        }
        judgeListMethod(paramList, dtoList);

        //更新子订单表
        List<OrderChild> orderChildList = iOrderChildService.selectList(new EntityWrapper<OrderChild>()
                .in("main_order_id", orderGoodsId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        Map<String, OrderChild> childMap = new HashMap<>();
        BigDecimal totalMoney = new BigDecimal(0);
        if (CollectionUtils.isNotEmpty(orderChildList)) {
            for (OrderChild orderChild : orderChildList) {
                totalMoney = totalMoney.add(orderChild.getTotalPrice());
                childMap.put(orderChild.getId(), orderChild);
            }
        }
        Map<String, GoodsAndDetailDto> childNumMap = new HashMap<>();
        for (GoodsAndDetailDto detailDto : detailDtos) {
            childNumMap.put(detailDto.getOrderChildId(), detailDto);
            ProductDTO productDTO = new ProductDTO(detailDto.getProductId(), detailDto.getGoodsNum(), detailDto.getFreeFreightStatus());
            if (goodsMap.get(detailDto.getOrderGoodId()).getProductDTOList() != null) {
                //相同的productId则数量相加
                boolean hasProduct = false;
                for (ProductDTO productDTOL : goodsMap.get(detailDto.getOrderGoodId()).getProductDTOList()) {
                    if (productDTOL.getProductId().equals(detailDto.getProductId())) {
                        productDTOL.setNumber(productDTOL.getNumber() + detailDto.getGoodsNum());
                        hasProduct = true;
                        break;
                    }
                }
                if (!hasProduct) {
                    goodsMap.get(detailDto.getOrderGoodId()).getProductDTOList().add(productDTO);
                }
            } else {
                productDTOList = new ArrayList<>();
                productDTOList.add(productDTO);
                goodsMap.get(detailDto.getOrderGoodId()).setProductDTOList(productDTOList);
            }
        }

        BigDecimal freint = new BigDecimal(0);
        for (OrderGoods orderGoods : goodsList) {
            String key = orderGoods.getId();
            BaseResult freightResult = freightTemplateRpcService.calcFreight(JSONObject.toJSONString(goodsMap.get(key).getProductDTOList()), goodsMap.get(key).getOrderDetailParam().getAddressProvince());
            log.info("运费调用结果：" + JSONObject.toJSONString(freightResult));
            if (freightResult.getCode() == Constants.RESPONSE_CODE_200) {
                BigDecimal yunFreight = new BigDecimal(freightResult.getData().toString());
                if(!freightResult.getData().toString().equals(OrderConstans.freight_NO_0)) {
                    BigDecimal yz = yunFreight.divide(totalMoney, 8, BigDecimal.ROUND_HALF_UP);
                    for (OrderChild orderChild : orderChildList) {
                        //子订单是属于本主订单下面
                        if(orderChild.getMainOrderId().equals(orderGoods.getId())) {
                            //商品是否免运费
                            if(!childNumMap.get(orderChild.getId()).getFreeFreightStatus().equals(OrderConstans.FREE_FREIGHT_NO)) {
                                BigDecimal yf = orderChild.getTotalPrice().multiply(yz);
                                BigDecimal newBigDecimal = yf.setScale(2, BigDecimal.ROUND_HALF_UP);
                                orderChild.setFreight(newBigDecimal);
                                orderChild.setPayMoney(orderChild.getTotalPrice().add(orderChild.getFreight()));
                            }
                        }
                    }
                }


                freint = freint.add(yunFreight);
                orderGoods.setFreight(yunFreight);
            }
        }
        if (goodsList != null) {
            Boolean goodsResult = iOrderGoodsService.updateBatchById(goodsList);
            Boolean goodsResultY = iOrderChildService.updateBatchById(orderChildList);
            if (goodsResult && goodsResultY) {
                result.setTotalFreight(freint);
                result.setTotalPrice(totalMoney.add(freint));
            }
        }
        return result;
    }

    /**
     * 计算和更新预订单运费信息
     *
     * @param orderGoodsId 分组订单Id列表
     * @param province     省份
     * @return
     */
    @Override
    public OrderChildDto updatefreight(List<String> orderGoodsId, String province) {
        OrderChildDto result = new OrderChildDto();
        String goodIds = "('" + StringUtils.join(orderGoodsId, "','") + "')";
        List<GoodsAndDetailDto> detailDtos = orderChildMapper.selectOrderDetail(goodIds);
        List<ProductDTO> productDTOList;

        //初始化所有的订单
        List<OrderGoods> goodsList = iOrderGoodsService.selectList(new EntityWrapper<OrderGoods>()
                .in("id", orderGoodsId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        //更新子订单表
        List<OrderChild> orderChildList = iOrderChildService.selectList(new EntityWrapper<OrderChild>()
                .in("main_order_id", orderGoodsId).eq("logic_delete", Constants.DEL_LOGIC_NORMAL));

        Map<String, OrderChild> childMap = new HashMap<>();
        BigDecimal totalMoney = new BigDecimal(0);
        if (CollectionUtils.isNotEmpty(orderChildList)) {
            for (OrderChild orderChild : orderChildList) {
                totalMoney = totalMoney.add(orderChild.getTotalPrice());
                childMap.put(orderChild.getId(), orderChild);
            }
        }
        Map<String, GoodsAndDetailDto> childNumMap = new HashMap<>();
        List<ProductDTO> proList = new ArrayList<>();
        BigDecimal freint = new BigDecimal(0);
        for (OrderGoods orderGoods : goodsList) {
            for (GoodsAndDetailDto detailDto : detailDtos) {
                childNumMap.put(detailDto.getOrderChildId(), detailDto);
                ProductDTO productDTO = new ProductDTO(detailDto.getProductId(), detailDto.getGoodsNum(), detailDto.getFreeFreightStatus());
                proList.add(productDTO);
            }

            //合并相同的商品id
            Map<String, ProductDTO> productDTOMap = new HashMap<>();
            for (ProductDTO productDTO : proList) {
                if (productDTOMap.get(productDTO.getProductId()) != null) {
                    productDTOMap.get(productDTO.getProductId()).setNumber(productDTOMap.get(productDTO.getProductId()).getNumber() + productDTO.getNumber());
                } else {
                    productDTOMap.put(productDTO.getProductId(), productDTO);
                }
            }
            String key = orderGoods.getId();
            BaseResult freightResult = freightTemplateRpcService.calcFreight(JSONObject.toJSONString(productDTOMap.values()), province);
            log.info("运费调用结果：" + JSONObject.toJSONString(freightResult));
            if (freightResult.getCode() == Constants.RESPONSE_CODE_200) {
                BigDecimal yunFreight = new BigDecimal(freightResult.getData().toString());
                if(!freightResult.getData().toString().equals(OrderConstans.freight_NO_0)) {
                    BigDecimal yz = yunFreight.divide(totalMoney, 8, BigDecimal.ROUND_HALF_UP);
                    for (OrderChild orderChild : orderChildList) {
                        //子订单是属于本主订单下面
                        if(orderChild.getMainOrderId().equals(orderGoods.getId())) {
                            //商品是否免运费
                            if(!childNumMap.get(orderChild.getId()).getFreeFreightStatus().equals(OrderConstans.FREE_FREIGHT_NO)) {
                                BigDecimal yf = orderChild.getTotalPrice().multiply(yz);
                                BigDecimal newBigDecimal = yf.setScale(2, BigDecimal.ROUND_HALF_UP);
                                orderChild.setFreight(newBigDecimal);
                                orderChild.setPayMoney(orderChild.getTotalPrice().add(orderChild.getFreight()));
                            }
                        }
                    }
                }
                freint = freint.add(yunFreight);
                orderGoods.setFreight(yunFreight);
            }
        }
        if (goodsList != null) {
            Boolean goodsResult = iOrderGoodsService.updateBatchById(goodsList);
            Boolean goodsResultY = iOrderChildService.updateBatchById(orderChildList);
            if (goodsResult && goodsResultY) {
                result.setTotalFreight(freint);
                result.setTotalPrice(totalMoney.add(freint));
            }
        }
        return result;
    }


    /**
     * 计算商品的运费
     *
     * @param productJson 商品id和数量的集合
     * @param addressId   收货省份名称
     * @return
     */
    @Override
    public Double freightCalculate(String productJson, String addressId) {

        BaseResult result = freightTemplateRpcService.calcFreight(productJson, addressId);
        return Double.valueOf(result.getData().toString());
    }
}

